import axios from 'axios'

const service = axios.create({

  baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:3000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('auth_token')
    if (token && !config.headers.Authorization) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

//响应拦截器
service.interceptors.response.use(
  (response) => {
    // 保持后端原始响应结构
    return response.data
  },
  (error) => {
    // 错误处理
    const errorMessage = error.response?.data?.message || 
                        error.response?.data?.msg ||
                        error.message ||
                        '请求失败'
    
    // 401跳转登录
    if (error.response?.status === 401) {
      window.location.href = '/login'
    }
    
    return Promise.reject(errorMessage)
  }
)

export default service